
const { addZero,$await } = require('../../../utils/util');  // 格式化时间
import {commonAPI} from '../../../api/common/index'
const request = require('../../../utils/request.js');  
const seeFm = require('../../../config.js')
const util = require('../../../utils/util.js');  
let app = getApp();
var timer = 0;
var topArr=[];
var nowLivePlay = 0;
Component({
	data: {
    avatar:seeFm.imgUrlAvatar+'/',
    page:'1',
		Index: 0,
		tableData: [
		
    ],
    height:0,
    noDate:0,
    noData:0,
  },
  properties:{
    channel_number:{
        type:String,
        value:''
    },
    programe_number:{
        type:String,
        value:''
    },
    heightchild1:{
      type:Number,
      value:''
    },
    heightchild:{
      type:Number,
      value:''
    },
    heightfather:{
      type:Number,
      value:''
    },
  },
  observers : {
    
  },
  // 组件生命周期
  lifetimes: {
    // 在组件实例进入页面节点树时执行
    created() {
      
    },
    attached() {
      let query = this.createSelectorQuery().in(this)
      query.select('.container').boundingClientRect((rect)=>{
          let scrollHeight = (Number(rect.height.toFixed(0)))*2-160+'rpx'
          this.setData({scrollHeight})
      }).exec()
      this.getDate();
    },
    
  },
  methods:{
    todetail: function(e){
      const { id } = e.currentTarget.dataset;
      wx.navigateTo({
        url: `/pages/shortVideo/index?number=${id}`
      })
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    scrolltolower: function () {
      setTimeout(() => {
          this.getDate();
      }, 300);
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    scrolltoupper: function () {
      // 标题栏显示刷新图标，转圈圈
      wx.showNavigationBarLoading()
      // 请求最新数据
      this.setData({
        page:'1'
      })
      this.getDate();
      setTimeout(() => {
          // 标题栏隐藏刷新转圈圈图标
          wx.hideNavigationBarLoading()
      }, 1000);
    },
    //异步获取数据
    async getDate(){
      let params = {
        'channel_number':this.data.channel_number,
        'programe_number':this.data.programe_number,
        'page':this.data.page
      }
      const [err,res] = await $await(commonAPI.videoList({...params}))
      if(res){
        if(this.data.page == '1' && res.programme_list.length == '0'){
          let query = this.createSelectorQuery().in(this)
          query.select('.container').boundingClientRect((rect)=>{
              let scrollHeight = (Number(rect.height.toFixed(0)))*2-700+'rpx'
              console.log(scrollHeight);
              this.setData({scrollHeight})
          }).exec()
          res.recommend_list.forEach(element => {
            element.url = element.playurl;
            element.videoSrc = element.playurl;
            element.poster = element.cover[0];
            element.startPlay = true;
            element.play = false;
            element.sliderValue = 0;
            element.process_duration = "00:00";
            element.total_duration=this.formatSeconds(element.duration) // 总时长
            element.full = false;
            element.duration=element.total_duration // 总时长
          });
          if(res.recommend_list.length>0){
            nowLivePlay = res.recommend_list[0].id
          }
          if(this.data.page == 1){
            this.setData({
              tableData:res.recommend_list
            })
          }else{
            this.setData({
              tableData:this.data.tableData.concat(res.recommend_list)
            })
          }
          // wx.nextTick(this.getId())
          this.setData({
            page:Number(this.data.page)+1
          })
          for(var i = 0; i<this.data.tableData.length; i++){
            if (i==0){
              if(this.data.tableData[i].play == false){
                this.setData({
                  ['tableData['+i+'].play'] : true
                })
                let videoId = 'myVideo'+this.data.tableData[i].id;
                let videoContext1 = wx.createVideoContext(videoId,this);
                videoContext1.play();
              }else{
                this.setData({
                  ['tableData['+i+'].play'] : false
                })
                let videoId = 'myVideo'+this.data.tableData[i].id;
                let videoContext1 = wx.createVideoContext(videoId,this);
                console.log(videoId)
                videoContext1.stop();
              }
            }else{
              this.setData({
                ['tableData['+i+'].play'] : false
              })
              let videoId1 = 'myVideo'+this.data.tableData[i].id;
              let videoContext2 = wx.createVideoContext(videoId1,this);
              videoContext2.stop();
            }
          }
          this.setData({
            noDate:1,
          })
        }else{
          if(res.programme_list.length == '0'){
            this.setData({
              noData:1,
            })
          }
          res.programme_list.forEach(element => {
            element.url = element.playurl;
            element.videoSrc = element.playurl;
            element.poster = element.cover[0];
            element.startPlay = true;
            element.play = false;
            element.sliderValue = 0;
            element.process_duration = "00:00";
            element.total_duration=this.formatSeconds(element.duration) // 总时长
            element.full = false;
            element.duration=element.total_duration // 总时长
          });
          if(res.programme_list.length>0){
            nowLivePlay = res.programme_list[0].id
          }
          if(this.data.page == 1){
            this.setData({
              tableData:res.programme_list
            })
          }else{
            this.setData({
              tableData:this.data.tableData.concat(res.programme_list)
            })
          }
          // wx.nextTick(this.getId())
          this.setData({
            page:Number(this.data.page)+1
          })
          for(var i = 0; i<this.data.tableData.length; i++){
            if (i==0){
              if(this.data.tableData[i].play == false){
                this.setData({
                  ['tableData['+i+'].play'] : true
                })
                let videoId = 'myVideo'+this.data.tableData[i].id;
                let videoContext1 = wx.createVideoContext(videoId,this);
                videoContext1.play();
              }else{
                this.setData({
                  ['tableData['+i+'].play'] : false
                })
                let videoId = 'myVideo'+this.data.tableData[i].id;
                let videoContext1 = wx.createVideoContext(videoId,this);
                console.log(videoId)
                videoContext1.stop();
              }
            }else{
              this.setData({
                ['tableData['+i+'].play'] : false
              })
              let videoId1 = 'myVideo'+this.data.tableData[i].id;
              let videoContext2 = wx.createVideoContext(videoId1,this);
              videoContext2.stop();
            }
          }
          if(res.programme_list.length == '0'){
            console.log('111111')
          }
        }
        for(let i=0;i<this.data.tableData.length;i++){
					this.setData({
						['tableData['+i+'].comment']:util.toFix(Number(this.data.tableData[i].comment),10000,'w')
					})
					this.setData({
						['tableData['+i+'].star']:util.toFix(Number(this.data.tableData[i].star),10000,'w')
					})
				}
      }
    },
    getId: function() {
      let top_num=this.data.tableData.length
      for (let i =0; i < top_num; i++) {
        topArr[i] = 0;
        const query = wx.createSelectorQuery().in(this)
        query.select('#myVideo' + this.data.tableData[i].id).boundingClientRect() //获取节点位置信息的查询请求
        query.selectViewport().scrollOffset(); // 获取页面滑动位置的查询请求
        query.exec((res) => {
          console.log(res)
          topArr[i] = res[0].top; //节点的上边界坐标
        })
      }
    },
    scroll: function(res) {
      console.log(res)
      let that = this;
      let top = res.detail.scrollTop;
      topArr = topArr.sort((x, y) => {
        return x - y
      })
      if (timer != 0) {
        clearTimeout(timer);
      }
      timer = setTimeout(function() {
        let Index_num = that.data.Index
        for (let j = 0; j < topArr.length; j++) {
          if (topArr[j] > top) {
            that.setData({
              Index: that.data.tableData[j].id
            })
            let string0 = 'myVideo' + nowLivePlay + ''
            let videoContext0 = wx.createVideoContext(string0,that);
            videoContext0.stop();
            let string1 = 'myVideo' + that.data.tableData[j].id + ''
            let videoContext1 = wx.createVideoContext(string1,that);
            videoContext1.play();
            that.setData({
							['tableData['+j+'].play'] : true
						})
            nowLivePlay = that.data.tableData[j].id
            console.log(that.data.Index)
            return;
          }
        }
      }, 500);
    },
    onShareAppMessage: function (from) {
      if(from == 'button'){
        const promise = new Promise(resolve => {
          setTimeout(() => {
            resolve({
              title: '自定义转发标题'
            })
          }, 2000)
        })
        return {
          title: '自定义转发标题',
          path: '/page/user?id=123',
          promise 
        }
      }else{
        const promise = new Promise(resolve => {
          setTimeout(() => {
            resolve({
              title: '自定义转发标题'
            })
          }, 2000)
        })
        return {
          title: '自定义转发标题',
          path: '/page/user?id=123',
          promise 
        }
      }
    },
    // 播放
    playStart(e) {
      console.log(e.currentTarget.dataset)
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
          if(this.data.tableData[i].play == false){
            this.setData({
              ['tableData['+i+'].play'] : true
            })
            let videoId = 'myVideo'+this.data.tableData[i].id;
            let videoContext1 = wx.createVideoContext(videoId,this);
            console.log(videoId)
            videoContext1.play();
          }else{
            this.setData({
              ['tableData['+i+'].play'] : false
            })
            let videoId = 'myVideo'+this.data.tableData[i].id;
            let videoContext1 = wx.createVideoContext(videoId,this);
            console.log(videoId)
            videoContext1.stop();
          }
          
        }else{
          this.setData({
            ['tableData['+i+'].play'] : false
          })
          let videoId1 = 'myVideo'+this.data.tableData[i].id;
          let videoContext2 = wx.createVideoContext(videoId1,this);
          videoContext2.stop();
        }
        
      }
      console.log(this.data.tableData)
    },
    // 全屏/退出全屏
    fullScreen() {
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
          let videoId = 'myVideo'+this.data.tableData[i].id;
          let videoContext1 = wx.createVideoContext(videoId,this);					
          !this.data.tableData[i].full ? videoContext1.requestFullScreen() : videoContext1.exitFullScreen();
          this.setData({
            ['tableData['+i+'].full'] : !this.data.full
          })
        }
      }
    },
    // 完成一次拖动后触发的事件
    sliderChange(e) {
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
          let videoId = 'myVideo'+this.data.tableData[i].id;
          let videoContext1 = wx.createVideoContext(videoId,this);					
          if (this.data.tableData[i].duration) {
            // 视频跳转到指定位置
            videoContext1.seek(e.detail.value / 100 * this.data.tableData[i].duration);
            this.setData({
              ['tableData['+i+'].sliderValue']: e.detail.value,
              ['tableData['+i+'].updateState'] : true
            })
          }
        }
      }
    },
    // 拖动过程中触发的事件
    sliderChanging(e) {
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
            this.setData({
              ['tableData['+i+'].updateState']: false// 拖动过程中不允许更新进度条
            })
        }
      }
    },
    // 播放进度
    bindtimeupdateFun(e) {
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
          // if(this.data.tableData[i].updateState){
            let sliderValue = e.detail.currentTime / e.detail.duration * 100;
            console.log(sliderValue)
            this.setData({
              ['tableData['+i+'].sliderValue']: sliderValue,
              ['tableData['+i+'].duration']: e.detail.duration,
              ['tableData['+i+'].total_duration']: this.formatSeconds(e.detail.duration), // 总时长 格式 00:00
              ['tableData['+i+'].process_duration']: this.formatSeconds(e.detail.currentTime), // 进度 格式 00:00
            })
          // }
        }
      }
    },
    // 结束
    bindEndedFun(e){
      for(var i = 0; i<this.data.tableData.length; i++){
        if (e.currentTarget.dataset['index'] === this.data.tableData[i].id){
            this.setData({
              ['tableData['+i+'].play']: false// 拖动过程中不允许更新进度条
            })
            let videoId = 'myVideo'+this.data.tableData[i].id;
            let videoContext1 = wx.createVideoContext(videoId,this);
            videoContext1.stop();
        }
      }
    },
    // 格式化视频时长  格式 00:00
    formatSeconds(value) {
      if (value == undefined) {
        value = 0;
      }
      var second = parseInt(value); // 秒
      var min = 0; // 分
      var hour = 0; // 小时
      if (second > 60) {
        min = parseInt(second / 60);
        second = parseInt(second % 60);
        if (min > 60) {
          hour = parseInt(min / 60);
          min = parseInt(min % 60);
        }
      }
      
      var result = "";
      // if (hour > 0) {
      //   hour = addZero(parseInt(hour));
      //   result = hour + ":";
      // }
      if (min > 0) {
        min = addZero(parseInt(min));
        result = min + ":";
      }else{
        result = "00:";
      }
      if(second > 0){
        second = addZero(parseInt(second));
        result = result + second;
      }else{
        result = result + '00';
      }
      return result;
    },
  },

	
})